package com.sh169.action.auth;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.nutz.dao.Dao;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import com.sh169.pojos.RoleUserRelation;
import com.sh169.pojos.User;
import com.sh169.service.auth.AuthHomeService;
import com.sh169.util.Md5;
import com.sh169.util.Validate;

@At("/auth")
@IocBean(name="authAuthHome")
@InjectName("authAuthHome")
public class AuthHome {
	@Inject("refer:dao")
	private Dao dao;
	@Inject("refer:authHomeService")
	private AuthHomeService authHomeService;
	@At("/user/regist")
	@Ok("redirect:/regist.jsp")
	public void regist(HttpServletRequest req,@Param("..")User user,@Param("password2")String password2) throws Exception{
		if("post".equalsIgnoreCase(req.getMethod())&&checkRegistUserAttrs(password2,user,req)){
			if(dao.fetch(User.class,user.getUsername())!=null){
				req.getSession().setAttribute("error", "此用户名已存在");
				return ;
			}
			User u = new User();
			u.setNickName(user.getNickName());
			u.setUsername(user.getUsername());
			u.setPassword(Md5.encode(user.getUsername()+user.getPassword()));
			u.setEmail(user.getEmail());
			u.setType(User.TYPE_USER);
			u.setLastLoginIp(req.getRemoteAddr());
			u.setLastLoginTime(new Date());
			u.setRegistIp(req.getRemoteAddr());
			u.setRegistTime(new Date());
			u.setState(User.STATE_VERIFY);
			dao.insert(u);
			RoleUserRelation rur = new RoleUserRelation();
			rur.setRoleid("user");
			rur.setUserid(u.getId());
			dao.fastInsert(rur);
			req.getSession().setAttribute("error", "success");
		}
	}
	/**
	 * 
	 * @param user
	 * @param request
	 */
	private boolean checkRegistUserAttrs(String password2,User user ,HttpServletRequest request){
		user.setId(null);
		boolean result = true;
		if(result&&!Validate.isInLength(user.getUsername(), 4, 16)){
			request.getSession().setAttribute("error", "帐号长度在4-16个字符");
			result = false;
		}
		if(result&&!Validate.isEmail(user.getEmail())){
			request.getSession().setAttribute("error", "emai格式不正确");
			result = false;
		}
		if(result&&!Validate.isInLength(user.getPassword(), 4, 16)){
			request.getSession().setAttribute("error", "密码长度在4-16个字符");
			result = false;
		}
		if(result&&!user.getPassword().equals(password2)){
			request.getSession().setAttribute("error", "重复密码不同");
			result = false;
		}
		return result;
	}
	
	public AuthHomeService getAuthHomeService() {
		return authHomeService;
	}
	public void setAuthHomeService(AuthHomeService authHomeService) {
		this.authHomeService = authHomeService;
	}
	public Dao getDao() {
		return dao;
	}
	public void setDao(Dao dao) {
		this.dao = dao;
	}
}
